/**  
* @Title: MtonsUtils.java
* @Package cn.net.mtons.core.weixin
* @Description: TODO
* @author ma jinjian  
* @date 2016年2月3日 下午11:21:20
* @version V1.0  
*/ 
package cn.net.mtons.weixin.utils;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.PrintWriter;
import java.io.StringWriter;

import javax.servlet.http.HttpServletRequest;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.log4j.Logger;
import org.codehaus.jettison.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import cn.net.mtons.weixin.MtonsWeixinVO;

/**
 * @ClassName: MtonsUtils
 * @Description: 微信工具类:
 * 			1: 发送GET请求
 * 			2：发送POST请求
 * 			3: 获取POST数据(接受到的消息)
 * @author ma jinjian
 * @date 2016年2月3日 下午11:21:20
 *
 */
public class MtonsUtils {

	private static Logger logger = Logger.getLogger("command");
	
	private static Logger netLog = Logger.getLogger("netlog");
	
	/**
	* @Title: sendGet
	* @Description: 发送GET请求, url后已经拼接各参数
	* @param @param url
	* @param @return
	* @return String 
	* @throws
	*/ 
	public static String sendGet(String url){
		HttpClient client = new HttpClient();
		HttpMethod getMethod = new GetMethod(url);
		try{
			client.executeMethod(getMethod);
			String returnJson = getMethod.getResponseBodyAsString();
			logger.info(returnJson);
			JSONObject JSONObject = new JSONObject(returnJson);
			if(JSONObject.has("errcode")){
				if(JSONObject.getInt("errcode") == 42001 || JSONObject.getInt("errcode") == -1){
					sendGet(url);
				}
			}
			return returnJson;
		} catch (Exception e){
			StringWriter sw = new StringWriter();  
            PrintWriter pw = new PrintWriter(sw);  
            e.printStackTrace(pw);
            netLog.warn("\r\n" + sw.toString() + "\r\n");
		}
		return null;
	}
	
	/**
	* @Title: sendPost
	* @Description: 发送POST请求, 各个参数放入MAP中
	* @param @param url
	* @param @param map
	* @param @return
	* @return String 
	* @throws
	*/ 
	public static void sendPost(MtonsWeixinVO vo){
		try {
			PostMethod method = new PostMethod(vo.getUrl());
			method.setRequestHeader("Content-Type","application/json");
			RequestEntity entity = new StringRequestEntity(vo.getJson(), null, "utf-8");
			method.setRequestEntity(entity);
			HttpClient client = new HttpClient();
			client.executeMethod(method);
			logger.debug("POST请求的Json字符串：");
			logger.debug(vo.getJson());
		} catch (Exception e) {
			StringWriter sw = new StringWriter();  
            PrintWriter pw = new PrintWriter(sw);  
            e.printStackTrace(pw);
            netLog.warn("\r\n" + sw.toString() + "\r\n");
		}
	}
	
	/**
	* @Title: getPostData
	* @Description: 获取POST数据(接受到的消息)
	* @param @param request
	* @param @return
	* @return Object 
	* @throws
	*/ 
	public static Object getPostData(HttpServletRequest request){
		try {
			String data = "";
			StringBuffer stringBuffer = new StringBuffer();
			BufferedReader reader = request.getReader();
			String line = reader.readLine();
			while(line != null){
				stringBuffer.append(line);
				line = reader.readLine();
			}
			data = stringBuffer.toString();
			logger.info("获取POST数据字符串：");
			logger.info(data);
			return data;
		} catch (Exception e) {
			StringWriter sw = new StringWriter();  
            PrintWriter pw = new PrintWriter(sw);  
            e.printStackTrace(pw);
            netLog.warn("\r\n" + sw.toString() + "\r\n");
		}
		return null;
	}
	
	public static Object analysisXML(String xmlString){
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document document = builder.parse(new InputSource(new ByteArrayInputStream(xmlString.getBytes("utf-8"))));
			NodeList list = document.getDocumentElement().getChildNodes();
			for(int i=0;i<list.getLength();i++){
				Node node = list.item(i);
				if(node.getNodeName().equals("MsgType")){
					String msgType = node.getTextContent();
					System.out.println("MsgType:"+msgType);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
	public static void main(String[] args) {
		MtonsUtils.analysisXML("<xml><ToUserName><![CDATA[刘娇]]></ToUserName><FromUserName><![CDATA[刘娇]]></FromUserName><CreateTime>1455372495043></CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[我爱你]]></Content></xml>");
	}
}
